using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace AdvancedLookup
{
    public partial class AdvancedLookupFieldEditor : UserControl, IFieldEditor
    {

        protected TextBox ItemLimitControl;
        protected TextBox PrefixControl;

        private AdvancedLookupField _currentAdvancedLookupField;

        uint _itemLimitValue = 10;

        uint _prefixValue = 1;


        readonly string[] _excludedFields = new[]{
      "_Author","_Category", "_CheckinComment", "_Comments", "_Contributor", "_Coverage", "_DCDateCreated",
      "_DCDateModified", "_EditMenuTableEnd", "_EditMenuTableStart", "_EndDate", "_Format",
      "_HasCopyDestinations", "_IsCurrentVersion", "_LastPrinted", "_Level", "_ModerationComments",
      "_ModerationStatus", "_Photo", "_Publisher", "_Relation", "_ResourceType", "_Revision",
      "_RightsManagement", "_SharedFileIndex", "_Source", "_SourceUrl", "_Status", "ActualWork",
      "AdminTaskAction", "AdminTaskDescription", "AdminTaskOrder", "AssignedTo", "Attachments",
      "AttendeeStatus", "Author", "BaseAssociationGuid", "BaseName", "Birthday", "Body",
      "BodyAndMore", "BodyWasExpanded", "Categories", "CheckoutUser", "Comment", "Comments", "Completed",
      "Created", "Created_x0020_By", "Created_x0020_Date", "DateCompleted", "DiscussionLastUpdated",
      "DiscussionTitle", "DocIcon", "DueDate", "Editor", "EmailBody", "EmailCalendarDateStamp",
      "EmailCalendarSequence", "EmailCalendarUid", "EndDate", "EventType", "Expires",
      "ExtendedProperties", "fAllDayEvent", "File_x0020_Size", "File_x0020_Type", "FileDirRef",
      "FileLeafRef", "FileRef", "FileSizeDisplay", "FileType", "FormData", "FormURN", "fRecurrence",
      "FSObjType", "FullBody", "Group", "GUID", "HasCustomEmailBody", "Hobbies", "HTML_x0020_File_x0020_Type",
      "IMAddress", "ImageCreateDate", "ImageHeight", "ImageSize", "ImageWidth", "Indentation", "IndentLevel",
      "InstanceID", "IsActive", "IsSiteAdmin", "ItemChildCount", "Keywords", "Last_x0020_Modified", "LessLink",
      "LimitedBody", "LinkDiscussionTitle", "LinkDiscussionTitleNoMenu", "LinkFilename", "LinkFilenameNoMenu",
      "LinkIssueIDNoMenu", "LinkTitle", "LinkTitleNoMenu", "MasterSeriesItemID", "MessageBody", "MessageId",
      "MetaInfo", "Modified", "Modified_x0020_By", "MoreLink", "Notes", "Occurred", "ol_Department",
      "ol_EventAddress", "owshiddenversion", "ParentFolderId", "ParentLeafName", "ParentVersionString",
      "PendingModTime", "PercentComplete", "PermMask", "PersonViewMinimal", "Picture", "PostCategory",
      "Priority", "ProgId", "PublishedDate", "QuotedTextWasExpanded", "RecurrenceData", "RecurrenceID",
      "RelatedIssues", "RelevantMessages", "RepairDocument", "ReplyNoGif", "RulesUrl", "ScopeId", "SelectedFlag",
      "SelectFilename", "ShortestThreadIndex", "ShortestThreadIndexId", "ShortestThreadIndexIdLookup",
      "ShowCombineView", "ShowRepairView", "StartDate", "StatusBar", "SystemTask", "TaskCompanies",
      "TaskDueDate", "TaskGroup", "TaskStatus", "TaskType", "TemplateUrl", "ThreadIndex", "Threading",
      "ThreadingControls", "ThreadTopic", "Thumbnail", "TimeZone", "ToggleQuotedText", "TotalWork",
      "TrimmedBody", "UniqueId", "VirusStatus", "WebPage", "WorkAddress", "WorkflowAssociation",
      "WorkflowInstance", "WorkflowInstanceID", "WorkflowItemId", "WorkflowListId", "WorkflowVersion",
      "xd_ProgID", "xd_Signature", "XMLTZone", "XomlUrl"
    };

        protected DropDownList ListTargetWeb;
        protected DropDownList ListTargetList;
        protected DropDownList ListTargetColumn;
        protected CheckBoxList DependentCheckBoxList;
        protected CheckBoxList CamlQueryFieldsCheckBoxList;

        protected Label LblTargetWeb;
        protected Label LblTargetList;

        protected HtmlGenericControl SpanDocLibWarning;
        protected HtmlGenericControl SpanLengthWarning;


        protected TextBox DialogPageUrlTextBox;
        protected TextBox DialogPageWidthTextBox;
        protected TextBox DialogPageHeightTextBox;
        protected TextBox QueryStringParamTextBox;
        protected TextBox CamlQueryTextBox;
        protected TextBox InitValueQueryStringParamTextBox;

        /// <summary>
        /// Method called when the editor control gets loaded
        /// </summary>
        /// <param name="field"></param>
        public void InitializeWithField(SPField field)
        {
            _currentAdvancedLookupField = field as AdvancedLookupField;

            EnsureChildControls();

            if (_currentAdvancedLookupField != null)
            {
                if (!IsPostBack)
                {
                    TargetWebId = _currentAdvancedLookupField.LookupWebId.ToString();

                    TargetListId = _currentAdvancedLookupField.LookupList;

                    TargetColumnInternalName = _currentAdvancedLookupField.LookupField;

                    DialogPageUrl = DialogPageUrlTextBox.Text = _currentAdvancedLookupField.DialogPageUrl;

                    DialogPageWidth = DialogPageWidthTextBox.Text = _currentAdvancedLookupField.DialogWidth;

                    DialogPageHeight = DialogPageHeightTextBox.Text = _currentAdvancedLookupField.DialogHeight;

                    QueryStringParam = QueryStringParamTextBox.Text = _currentAdvancedLookupField.QueryStringParam;

                    CamlQuery = CamlQueryTextBox.Text = _currentAdvancedLookupField.CamlQuery;

                    InitValueQueryStringParam = InitValueQueryStringParamTextBox.Text = _currentAdvancedLookupField.InitValueQueryStringParam;
                }
            }

            if (!IsPostBack)
            {
                SetTargetWeb();

                LblTargetWeb.Text = ListTargetWeb.SelectedItem.Text;

                LblTargetList.Text = ListTargetList.SelectedItem.Text;

                SetControlVisibility();
            }
        }

        private void SetControlVisibility()
        {
            string referrer = Request.Url.AbsoluteUri;

            if (!string.IsNullOrEmpty(referrer))
            {
                if (referrer.IndexOf("_layouts/fldNew.aspx") > -1
                  || referrer.IndexOf("_layouts/FldNewEx.aspx") > -1) // adding new field
                {
                    LblTargetList.Visible = false;
                    LblTargetWeb.Visible = false;
                    ListTargetList.Visible = true;
                    ListTargetWeb.Visible = true;
                }
                else
                {
                    LblTargetList.Visible = true;
                    LblTargetWeb.Visible = true;
                    ListTargetList.Visible = false;
                    ListTargetWeb.Visible = false;
                }
            }
            if (SPContext.Current.List != null)
            {
                SpanDocLibWarning.Visible = (SPContext.Current.List.BaseType == SPBaseType.DocumentLibrary);
                SpanLengthWarning.Visible = (SPContext.Current.List.BaseType == SPBaseType.DocumentLibrary);
            }
        }

        private void SetTargetWeb()
        {
            ListTargetWeb.Items.Clear();

            List<ListItem> str = new List<ListItem>();

            SPSite site = SPControl.GetContextSite(Context);

            SPWebCollection webCollection = site.AllWebs;

            string contextWebId = SPControl.GetContextWeb(Context).ID.ToString();

            foreach (SPWeb web in webCollection)
            {
                if (web.DoesUserHavePermissions(
                  SPBasePermissions.ViewPages | SPBasePermissions.OpenItems | SPBasePermissions.ViewListItems))
                {
                    str.Add(new ListItem(web.Title, web.ID.ToString()));
                }
            }

            if (str.Count > 0)
            {
                str.Sort(delegate(ListItem item1, ListItem item2)
                {
                    return item1.Text.CompareTo(item2.Text);
                });

                ListTargetWeb.Items.AddRange(str.ToArray());

                ListItem bitem = ListTargetWeb.Items.FindByValue(!string.IsNullOrEmpty(TargetWebId) ? TargetWebId : contextWebId);

                ListTargetWeb.SelectedIndex = bitem != null ? ListTargetWeb.Items.IndexOf(bitem) : 0;

                SetTargetList(ListTargetWeb.SelectedItem.Value, true);
            }
        }

        private void SetTargetList(string selectedWebId, bool setTargetColumn)
        {
            ListTargetList.Items.Clear();

            if (!string.IsNullOrEmpty(selectedWebId))
            {
                SPSite spSite = SPControl.GetContextSite(Context);

                SPWeb spWeb = spSite.OpenWeb(new Guid(selectedWebId));

                SPListCollection spListCollection = spWeb.Lists;

                foreach (SPList spList in spListCollection)
                {
                    if (!spList.Hidden)
                    {
                        ListTargetList.Items.Add(new ListItem(spList.Title, spList.ID.ToString().Trim(new[] { '{', '}' })));
                    }
                }

                ListTargetList.SelectedValue = TargetListId.Trim(new[] { '{', '}' });

                if (setTargetColumn)
                {
                    SetTargetColumn(selectedWebId, ListTargetList.SelectedItem.Value);
                }
            }
        }

        private void SetTargetColumn(string webId, string selectedListId)
        {
            ListTargetColumn.Items.Clear();

            if (!string.IsNullOrEmpty(webId) && !string.IsNullOrEmpty(selectedListId))
            {
                SPSite spSite = SPControl.GetContextSite(Context);

                SPWeb spWeb = spSite.OpenWeb(new Guid(webId));

                SPList list = spWeb.Lists[new Guid(selectedListId)];

                PopulateShowFieldDropDown(DependentCheckBoxList, list, OwnerListId, "", null);

                PopulateShowFieldDropDownEx(CamlQueryFieldsCheckBoxList, list, OwnerListId, "", null);

                SPFieldCollection fields = list.Fields;

                foreach (SPField spField in fields)
                {
                    if (CanFieldBeDisplayed(spField))
                    {
                        ListTargetColumn.Items.Add(new ListItem(
                          string.Format(CultureInfo.InvariantCulture, "{0}", spField.Title), spField.InternalName));
                    }
                }

                if (_currentAdvancedLookupField != null)
                {
                    SetSelectedfields(new List<string>(_currentAdvancedLookupField.AdditionalLookupFields.Split(';')),
                                      DependentCheckBoxList);

                    SetSelectedfields(new List<string>(_currentAdvancedLookupField.CamlQueryFields.Split(';')),
                                   CamlQueryFieldsCheckBoxList);
                }
            }
        }

        private bool CanFieldBeDisplayed(SPField f)
        {
            bool retval = false;

            if (f != null && !f.Hidden && (Array.IndexOf(_excludedFields, f.InternalName) < 0))
            {
                switch (f.Type)
                {
                    case SPFieldType.Computed:
                        if (((SPFieldComputed)f).EnableLookup)
                            retval = true;
                        break;
                    case SPFieldType.Calculated:
                        if (((SPFieldCalculated)f).OutputType == SPFieldType.Text)
                            retval = true;
                        break;
                    default:
                        retval = true;
                        break;
                }
            }

            return retval;
        }

        private string InitValueQueryStringParam
        {
            get
            {
                object o = ViewState["INIT_VALUE_QUERY_STRING_PARAM"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["INIT_VALUE_QUERY_STRING_PARAM"] = value; }
        }

        private string QueryStringParam
        {
            get
            {
                object o = ViewState["QUERY_STRING_PARAM"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["QUERY_STRING_PARAM"] = value; }
        }

        private string CamlQuery
        {
            get
            {
                object o = ViewState["CAML_QUERY"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["CAML_QUERY"] = value; }
        }

        private string DialogPageHeight
        {
            get
            {
                object o = ViewState["DIALOG_PAGE_HEIGHT"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["DIALOG_PAGE_HEIGHT"] = value; }
        }

        private string DialogPageWidth
        {
            get
            {
                object o = ViewState["DIALOG_PAGE_WIDTH"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["DIALOG_PAGE_WIDTH"] = value; }
        }

        private string DialogPageUrl
        {
            get
            {
                object o = ViewState["DIALOG_PAGE_URL"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["DIALOG_PAGE_URL"] = value; }
        }

        private string TargetWebId
        {
            get
            {
                object o = ViewState["TARGET_WEB_ID"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["TARGET_WEB_ID"] = value; }
        }

        private string TargetListId
        {
            get
            {
                object o = ViewState["TARGET_LIST_ID"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["TARGET_LIST_ID"] = value; }
        }

        private string TargetColumnInternalName
        {
            get
            {
                object o = ViewState["TARGET_COLUMN_ID"];
                return (o != null && !string.IsNullOrEmpty(o.ToString())) ? o.ToString() : string.Empty;
            }
            set { ViewState["TARGET_COLUMN_ID"] = value; }
        }

        static void AddFieldToDropDown(ListControl showField, SPField field, string strSelectedField, string extraText)
        {
            ListItem item = new ListItem();

            item.Text = field.Title + " " + field.AuthoringInfo + " ";

            if (!string.IsNullOrEmpty(extraText))
            {
                item.Text = item.Text + extraText;
            }

            item.Text = item.Text.Trim();

            if (showField is CheckBoxList)
            {
                item.Text = SPHttpUtility.HtmlEncode(item.Text);
            }

            item.Value = field.InternalName;

            if (field.InternalName == strSelectedField)
            {
                item.Selected = true;
            }

            showField.Items.Add(item);
        }

        protected Guid OwnerListId
        {
            get
            {
                string str = Request.QueryString.Get("List");

                if (!string.IsNullOrEmpty(str))
                {
                    return new Guid(str);
                }

                return Guid.Empty;
            }
        }

        static void PopulateShowFieldDropDownEx(ListControl showField, SPList lookupToList, Guid ownerListId, string strSelectedField, string[] excludedShowFields)
        {
            showField.Items.Clear();

            foreach (SPField field in lookupToList.Fields)
            {
                if (field.Hidden || ((excludedShowFields != null) && (Array.IndexOf<string>(excludedShowFields, field.InternalName) >= 0)))
                {
                    continue;
                }

                AddFieldToDropDown(showField, field, strSelectedField, null);
            }
        }

        static void PopulateShowFieldDropDown(ListControl showField, SPList lookupToList, Guid ownerListId, string strSelectedField, string[] excludedShowFields)
        {
            showField.Items.Clear();
            foreach (SPField field in lookupToList.Fields)
            {
                if (field.Hidden || ((excludedShowFields != null) && (Array.IndexOf<string>(excludedShowFields, field.InternalName) >= 0)))
                {
                    continue;
                }
                if (lookupToList.HasExternalDataSource)
                {
                    if (!field.InternalName.StartsWith("bdil", StringComparison.Ordinal) && (field.InternalName != "BdcIdentity"))
                    {
                        AddFieldToDropDown(showField, field, strSelectedField, null);
                    }
                    continue;
                }
                if (((((field.Type == SPFieldType.Counter) || (field.Type == SPFieldType.Text)) || ((field.Type == SPFieldType.Number) || (field.Type == SPFieldType.DateTime))) || ((field.Type == SPFieldType.Computed) && ((SPFieldComputed)field).EnableLookup)) || ((field.Type == SPFieldType.Calculated) && (((SPFieldCalculated)field).OutputType == SPFieldType.Text)))
                {
                    AddFieldToDropDown(showField, field, strSelectedField, null);
                    continue;
                }
                if ((ShouldBeCountRelated(field, ownerListId) && (!(field is SPFieldLookup) || string.IsNullOrEmpty((field as SPFieldLookup).PrimaryFieldId))) && !(showField is CheckBoxList))
                {
                    AddFieldToDropDown(showField, field, strSelectedField, SPResource.GetString("LookupCountRelatedTag", new object[0]));
                    // countRelatedLookups.Add(field.InternalName);
                }
            }
        }

        static bool ShouldBeCountRelated(SPField field, Guid ownerListId)
        {
            bool flag = false;

            if (((field != null) && (field.Type == SPFieldType.Lookup)) && (!(field as SPFieldLookup).IsDependentLookup && (ownerListId != Guid.Empty)))
            {
                SPFieldLookup lookup = (SPFieldLookup)field;

                string lookupList = lookup.LookupList;

                Guid guid = (field.ParentList != null) ? field.ParentList.ID : Guid.Empty;

                if (IsGuid(lookupList))
                {
                    Guid guid2 = new Guid(lookupList);

                    flag = (((guid != ownerListId) || (guid == Guid.Empty)) && ((guid2 == ownerListId) && !lookup.CountRelated)) && !lookup.AllowMultipleValues;
                }
            }
            return flag;

        }

        static bool IsGuid(string strId)
        {
            if (string.IsNullOrEmpty(strId))
            {
                return false;
            }
            strId = strId.Trim();
            if (strId.Length < 0x20)
            {
                return false;
            }
            if (strId.Contains("x") || strId.Contains("X"))
            {
                strId = strId.Replace(" ", "");

                return Regex.IsMatch(strId, @"^\{0[x|X][a-fA-F\d]{8},(0[x|X][a-fA-F\d]{4},){2}\{(0[x|X][a-fA-F\d]{2},){7}0[x|X][a-fA-F\d]{2}\}\}$", RegexOptions.Compiled);
            }
            return Regex.IsMatch(strId, @"^([a-fA-F\d]{8}-([a-fA-F\d]{4}-){3}[a-fA-F\d]{12}|\([a-fA-F\d]{8}-([a-fA-F\d]{4}-){3}[a-fA-F\d]{12}\)|\{[a-fA-F\d]{8}-([a-fA-F\d]{4}-){3}[a-fA-F\d]{12}\}|[a-fA-F\d]{32})$", RegexOptions.Compiled);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            ItemLimitControl.Text = _itemLimitValue.ToString();
            PrefixControl.Text = _prefixValue.ToString();
        }
        /// <summary>
        /// Method called when the user clicks ok.
        /// </summary>
        /// <param name="field"></param>
        /// <param name="bNewField"></param>
        public void OnSaveChange(SPField field, bool bNewField)
        {
            AdvancedLookupField advancedAdvancedLookupField = field as AdvancedLookupField;

            if (ItemLimitControl.Text != "")
                _itemLimitValue = UInt32.Parse(ItemLimitControl.Text);

            if (PrefixControl.Text != "")
                _prefixValue = UInt32.Parse(PrefixControl.Text);

            if (advancedAdvancedLookupField != null)
            {
                string col = ListTargetColumn.SelectedItem.Value;

                string list = ListTargetList.SelectedItem.Value;

                if (bNewField)
                {
                    advancedAdvancedLookupField.UpdateItemLimitProp(_itemLimitValue);

                    advancedAdvancedLookupField.UpdatePrefixProp(_prefixValue);

                    SPSite site = SPControl.GetContextSite(Context);

                    SPWeb web = site.OpenWeb(new Guid(ListTargetWeb.SelectedItem.Value));

                    advancedAdvancedLookupField.LookupWebId = web.ID;

                    advancedAdvancedLookupField.LookupList = "{" + list.Trim(new[] { '{', '}' }) + "}";
                }

                advancedAdvancedLookupField.Prefix = _prefixValue;

                advancedAdvancedLookupField.ItemLimit = _itemLimitValue;


                advancedAdvancedLookupField.LookupField = col;
                advancedAdvancedLookupField.DialogPageUrl = DialogPageUrlTextBox.Text;
                advancedAdvancedLookupField.DialogWidth = DialogPageWidthTextBox.Text;
                advancedAdvancedLookupField.DialogHeight = DialogPageHeightTextBox.Text;
                advancedAdvancedLookupField.QueryStringParam = QueryStringParamTextBox.Text;
                advancedAdvancedLookupField.CamlQuery = CamlQueryTextBox.Text;
                advancedAdvancedLookupField.InitValueQueryStringParam = InitValueQueryStringParamTextBox.Text;

                List<string> additionalLookupFieldsTmp = new List<string>();

                foreach (ListItem listItem in DependentCheckBoxList.Items)
                {
                    if (listItem.Selected)
                        additionalLookupFieldsTmp.Add(listItem.Value);
                }

                List<string> camlFieldsTmp = new List<string>();

                foreach (ListItem listItem in CamlQueryFieldsCheckBoxList.Items)
                {
                    if (listItem.Selected)
                        camlFieldsTmp.Add(listItem.Value);
                }

                advancedAdvancedLookupField.AdditionalLookupFields = string.Join(";", additionalLookupFieldsTmp.ToArray());

                advancedAdvancedLookupField.CamlQueryFields = string.Join(";", camlFieldsTmp.ToArray());

                CreateAdditionalLookupFields(advancedAdvancedLookupField, additionalLookupFieldsTmp);
            }
        }



        protected void CreateAdditionalLookupFields(AdvancedLookupField advancedLookupField, List<string> lookupColAdditionalFieldDisplayNames)
        {
            if (advancedLookupField != null && advancedLookupField.ParentList != null)
            {
                using (SPSite spSite = SPControl.GetContextSite(Context))
                {

                    SPList spListParent = advancedLookupField.ParentList;

                    foreach (ListItem listItem in DependentCheckBoxList.Items)
                    {
                        string internalName = string.Format("{0}_x003a_{1}",
                                                            string.IsNullOrEmpty(advancedLookupField.InternalName)
                                                                ? advancedLookupField.Title
                                                                : advancedLookupField.InternalName, listItem.Value);

                        if (spListParent.Fields.ContainsField(internalName))
                        {
                            DeleteHiddenField(spListParent, internalName);
                        }
                    }

                    foreach (string lookupColAdditionalFieldDisplayName in lookupColAdditionalFieldDisplayNames)
                    {
                        SPFieldLookup spFieldLookup =
                            (SPFieldLookup)
                            spListParent.Fields.CreateNewField(SPFieldType.Lookup.ToString(),
                                                               string.Format("{0}:{1}", string.IsNullOrEmpty(advancedLookupField.InternalName) ? advancedLookupField.Title : advancedLookupField.InternalName, lookupColAdditionalFieldDisplayName));

                        spFieldLookup.LookupList = advancedLookupField.LookupList;

                        spFieldLookup.LookupWebId = advancedLookupField.LookupWebId;

                        spFieldLookup.LookupField = lookupColAdditionalFieldDisplayName;

                        spFieldLookup.PrimaryFieldId = advancedLookupField.Id.ToString();

                        spFieldLookup.ReadOnlyField = true;

                        //spFieldLookup.Hidden = true;

                        spFieldLookup.AllowMultipleValues = advancedLookupField.AllowMultipleValues;

                        spFieldLookup.UnlimitedLengthInDocumentLibrary =
                            advancedLookupField.UnlimitedLengthInDocumentLibrary;

                        spFieldLookup.Direction = advancedLookupField.Direction;

                        spListParent.Fields.AddFieldAsXml(spFieldLookup.SchemaXml, true, SPAddFieldOptions.Default);
                    }
                    //}
                }
            }
        }

        protected void SelectedTargetWebChanged(Object sender, EventArgs args)
        {
            if (ListTargetWeb.SelectedIndex > -1)
            {
                SetTargetList(ListTargetWeb.SelectedItem.Value, true);
                Page.SetFocus(ListTargetList);
            }
        }

        protected void SelectedTargetListChanged(Object sender, EventArgs args)
        {
            if (ListTargetList.SelectedIndex > -1)
            {
                string webId = string.Empty;

                if (ListTargetWeb.Items.Count > 0)
                {
                    webId = ListTargetWeb.SelectedItem.Value;
                }
                else
                    if (!string.IsNullOrEmpty(TargetWebId))
                    {
                        webId = TargetWebId;
                    }

                SetTargetColumn(webId, ListTargetList.SelectedItem.Value);

                //SetTargetListView(webId, ListTargetList.SelectedItem.Value);

                Page.SetFocus(ListTargetColumn);
            }
        }

        private void SetSelectedfields(List<string> showFieldNames, CheckBoxList checkBoxList)
        {
            if ((showFieldNames != null) && (showFieldNames.Count != 0))
            {
                foreach (ListItem item in checkBoxList.Items)
                {
                    if (showFieldNames.Contains(item.Value))
                    {
                        item.Selected = true;
                    }
                }
            }
        }

        public bool DisplayAsNewSection
        {
            get
            {
                return true;
            }
        }
    }
}
